using Godot;
using System;

namespace Library {
	public class MusicPlayer : AudioStreamPlayer {
		public string index = "";
		public string Index {
			get => index;
			set {
				if (string.IsNullOrWhiteSpace(value)||!MusicController.Collection.ContainsKey(value)) {
					Stream = null;
					LoopStart = -1;
					LoopEnd = -1;
				}
				MusicController.Data data = MusicController.Collection[value];
				try {
					Stream = GD.Load<AudioStream>(data.File);
					LoopStart = data.LoopStart;
					LoopEnd = data.LoopEnd;
				} catch (Exception) {
					GD.PrintErr("[StreamedAudioManager] Failed to load stream from ", value);
				}
			}
		}
		public float Position {
			get => GetPlaybackPosition();
			set => Seek(value);
		}
		public float LoopStart { get; set; } = -1;
		public float LoopEnd { get; set; } = -1;

		public override void _Process(float delta) {
			if (LoopStart >= 0 && LoopEnd >= 0) {
				float pos = Position;
				if (pos > LoopEnd) {
					Position = LoopStart + (pos - LoopEnd);
				}
			}
		}
	}
}
